//获取和存储文件
var request = require('request'),
    https = require('https'),
    http = require('http'),
    fs = require("fs");
    logger = require("./logger.js");

function getAndSaveFile(imgUrl, savePath, fileName, callBack) {
    //logger.info("获取图片地址:" + imgUrl);
    try {
        if (imgUrl.startsWith("https")) {
            https.get(imgUrl, function (res) {
                var imgData = "";

                res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开

                res.on("data", function (chunk) {
                    imgData += chunk;
                });

                try {
                    res.on("end", function () {
                        fs.writeFile(savePath + fileName, imgData, "binary", function (err) {
                            if (err) {
                                logger.error(fileName + " 下载失败");
                            } else {
                                logger.info(fileName + " 下载成功");
                            }
                            callBack();
                        });

                    });
                } catch (e) {
                    logger.error("图片下载异常 :" + imgUrl, e);
                }
            });
        } else {
            http.get(imgUrl, function (res) {
                var imgData = "";

                res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开

                res.on("data", function (chunk) {
                    imgData += chunk;
                });

                try {
                    res.on("end", function () {
                        fs.writeFile(savePath + fileName, imgData, "binary", function (err) {
                            if (err) {
                                logger.error(fileName + " 下载失败");
                            } else {
                                logger.info(fileName + " 下载成功");
                            }
                            callBack();
                        });

                    });
                } catch (e) {
                    logger.error("图片下载异常 :" + imgUrl, e);
                }
            });
        }
    } catch (e) {
        logger.error("图片下载异常 :" + imgUrl);
        logger.error(e);
    }
}

module.exports = getAndSaveFile;